import { logout, getInfo } from '@/api/user'
import { setToken, removeToken ,getPersonName ,setName} from '@/utils/auth'
import { resetRouter } from '@/router'
import {  setPersonName, removePersonName } from '@/utils/auth'

import axios from 'axios'

const getDefaultState = () => {
  return {
    token: '',
    name: '',
    avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
    personName: getPersonName(),
    info: {},
    roles: []
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
    setToken(token)
  },
  SET_NAME: (state, name) => {
    setName(name)
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_INFO: (state, info) => {
    state.info = info
  },
  SET_PERSON_NAME: (state, personName) => {
    setPersonName(personName)
    state.personName = personName
  },
  SET_ROLES (state, roles) {
    state.roles = roles
  }
}

const actions = {
  // user login
  getAuthResult({ commit }, code) {
    return new Promise((resolve, reject) => {
      axios
        .post(process.env.VUE_APP_LOGINCB_API, { authCode: code })
        .then((res) => {
          const { data } = res
          commit('SET_TOKEN', data.accessToken)
          resolve(res)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // get user info
  GetInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        // console.log('userInfo response', response)
        const  data  = response
        commit('SET_NAME', data.name)
        commit('SET_AVATAR','https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif')
        commit('SET_INFO', data)
        commit('SET_PERSON_NAME', data.personName)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  Logout({ commit, state }) {
    return new Promise((resolve) => {
      logout()
        .then(() => {
          resolve()
        })
        .catch(() => {
          resolve()
        })
        .finally(() => {
          commit('RESET_STATE')
          removeToken()
          resetRouter()
        })
    })
  },

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

